package com.papper.common.service.sys;

import com.google.common.collect.Lists;
import com.papper.common.bean.sys.SysModel;
import com.papper.common.bean.sys.SysSystem;
import com.papper.common.config.StorageConstants;
import com.papper.common.mapper.sys.SysSystemMapper;
import com.papper.common.service.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Optional;

@Service("sysSystemService")
public class SysSystemService extends ServiceImpl<SysSystemMapper, SysSystem> {

	@Autowired
	SysModelService sysModelService;

	/**
	 * 查询当前系统信息.
	 *
	 * @return the sys system
	 */
	public SysSystem findSysSystem() {
		return findWithCode(StorageConstants.SystemCode());
	}

	/**
	 * 根据编号查询系统信息.
	 *
	 * @param systemCode the system code
	 * @return the sys system
	 */
	public SysSystem findWithCode(String systemCode) {
		if (systemCode == null || systemCode.isEmpty()) {
			return null;
		}
		Example example = new Example(SysSystem.class);
		example.createCriteria().andEqualTo("systemCode", systemCode);
		return findOne(example);
	}

	/**
	 * 删除系统+模块信息.
	 *
	 * @param sysSystem the id
	 */
	public void deleteWithModel(SysSystem sysSystem) {
		if (sysSystem != null) {
			List<SysModel> sysModelList = sysModelService.findBySystemId(sysSystem.getId(), null);
			Optional.ofNullable(sysModelList).orElse(Lists.newArrayList()).forEach(sm -> {
				sysModelService.deleteWithRes(sm.getId());
			});
			delete(sysSystem);
		}
	}
}